import 'package:casdon/modules/lifeCircle/data/model/life_topic_module.dart';
import 'package:casdon/modules/lifeCircle/domain/states/life_topic_list_state.dart';
import 'package:casdon/modules/lifeCircle/domain/usecase/life_user_topic_list_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class LifeUserTopicListNotifier
    extends AutoDisposeFamilyAsyncNotifier<LifeTopicListState, String> {
  late final String userId;
  int pageSize = 10;
  int pageNum = 1;

  @override
  Future<LifeTopicListState> build(String arg) async {
    userId = arg;

    return _fetchData();
  }

  Future<void> refresh() async {
    try {
      pageNum = 1;
      final newState = await _fetchData();
      state = AsyncValue.data(newState);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  Future<LifeTopicListState> _fetchData() async {
    final ret = await ref
        .read(lifeUserTopicListUsecaseProvider)
        .execute(userId: userId, pageNum: pageNum, pageSize: pageSize);
    // 用户帖子列表不需要关注状态，将所有 isFollow 设为 false
    final topics = (ret.rows ?? []).map((topic) {
      return LifeTopicModule.fromApi(topic);
    }).toList();
    return LifeTopicListState(
      data: topics,
      totalSize: ret.total,
      page: pageNum,
      pageSize: pageSize,
      isLoadingMore: false,
      hasMore: ret.total > (ret.rows ?? []).length,
    );
  }

  Future<void> loadMore() async {
    final current = state.valueOrNull;
    if (current == null || current.isLoadingMore || !current.hasMore) return;

    state = AsyncValue.data(current.copyWith(isLoadingMore: true));

    final nextPage = current.page + 1;
    final ret = await ref
        .read(lifeUserTopicListUsecaseProvider)
        .execute(userId: userId, pageNum: nextPage, pageSize: pageSize);

    // 用户帖子列表不需要关注状态，将所有 isFollow 设为 false
    final newTopics = (ret.rows ?? []).map((topic) {
      return LifeTopicModule.fromApi(topic).copyWith(isFollow: false);
    }).toList();

    state = AsyncValue.data(
      LifeTopicListState(
        data: [...current.data ?? [], ...newTopics],
        page: nextPage,
        totalSize: ret.total,
        pageSize: current.pageSize,
        isLoadingMore: false,
        hasMore:
            ret.total > (current.data ?? []).length + (ret.rows ?? []).length,
      ),
    );
  }

  /// 更新该用户所有 topic 的关注状态
  void updateAllTopicsFollowStatus(bool isFollowed) {
    final current = state.valueOrNull;
    if (current == null || current.data == null) return;

    final updatedData = current.data!.map((topic) {
      return topic.copyWith(isFollow: isFollowed);
    }).toList();

    state = AsyncValue.data(current.copyWith(data: updatedData));
  }

  void removeTopicById(String topicId) {
    final current = state.valueOrNull;
    final currentData = current?.data;
    if (current == null || currentData == null) return;

    final newData = currentData.where((topic) => topic.id != topicId).toList();
    final newState = current.copyWith(
      data: newData,
      totalSize: current.totalSize > 0 ? current.totalSize - 1 : 0,
      hasMore: newData.length < current.totalSize,
    );
    state = AsyncValue.data(newState);
  }

  void updateTopicLikeStatus(
    String topicId,
    bool isLiked,
    int likesCount,
  ) {
    final current = state.valueOrNull;
    final currentData = current?.data;
    if (current == null || currentData == null) return;

    final updated = currentData.map((topic) {
      if (topic.id != topicId) return topic;
      return topic.copyWith(isLike: isLiked, likes: likesCount);
    }).toList();

    state = AsyncValue.data(current.copyWith(data: updated));
  }
}

final lifeUserTopicListNotifierProvider =
    AutoDisposeAsyncNotifierProviderFamily<
      LifeUserTopicListNotifier,
      LifeTopicListState,
      String
    >(() => LifeUserTopicListNotifier());
